﻿using LettuceEncrypt.Accounts;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Quickly.Certs.Core.LettuceEncrypt
{
    public class DatabaseAccountStore : IAccountStore
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger _logger;

        public DatabaseAccountStore(
            IServiceProvider serviceProvider, 
            ILogger<DatabaseAccountStore> logger)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
        }

        public static IDatabaseAccountRepository GetRepository(IServiceProvider serviceProvider) => serviceProvider.GetRequiredService<IDatabaseAccountRepository>();

        public async Task<AccountModel?> GetAccountAsync(CancellationToken cancellationToken)
        {
            using (var serviceScope = _serviceProvider.CreateScope())
            {
                var repo = GetRepository(serviceScope.ServiceProvider);

                var account = await repo.GetAccountModelAsync(cancellationToken);

                if(account != null)
                {
                    _logger.LogDebug("Loaded account information from database: {Id}", account?.Id);
                    return account;
                }
            }

            _logger.LogDebug("Could not find account information in database");
            return default;
        }

        public async Task SaveAccountAsync(AccountModel account, CancellationToken cancellationToken)
        {
            _logger.LogTrace("Saving account informatino to database: {AccoundId}", account.Id);

            using (var serviceScope = _serviceProvider.CreateScope())
            {
                var repo = GetRepository(serviceScope.ServiceProvider);

                await repo.SaveAccountModelAsync(account, cancellationToken);

                _logger.LogDebug("Saved account information to database: {AccountId}", account.Id);
            }
        }
    }
}
